package net.dwade.livechat.websocket.loadrunner;

import lrapi.lr;
import net.dwade.livechat.websocket.client.ChatClient;
import net.dwade.livechat.websocket.client.ChatWebsocketClient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 该场景循环创建Websocket连接，不会保持已创建的会话，并且在连接之后发起订阅操作
 */
public class SubscritionConnectionAction {
	
	private static Logger logger = LoggerFactory.getLogger( SubscritionConnectionAction.class );
	
	private ChatClient client;

	public int init() throws Throwable {
		
		String userAgent = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36";
		String indexUrl = "http://10.255.201.166:10086/livechat-touch-client/index?tenantId=1000055&code=BS&channelType=1021";
		String pullUrl = "http://10.255.201.166:10086/livechat-touch-client/clientPull";
		String chatUrl = "ws://10.255.201.166:10086/livechat-touch-client/chat";
		String domain = "10.255.201.166:18800";
		String httpSessionId = null;
		
		//创建Websocket客户端
		client = new ChatWebsocketClient( userAgent, indexUrl, pullUrl, chatUrl, domain, httpSessionId );
		logger.info( "Creat websocket client: {}", client );
		
		//模拟index，clientPull
		client.index();
		client.clientPull();
		
		logger.info( "Websocket连接已就绪, chatSessionId:{}", client.getChatSessionId() );
		
		return 0;
	}

	public int action() throws Throwable {
		
		//再次创建连接之前，先关闭之前的连接
		try {
			client.disconnect();
		} catch (Exception e) {
			// ignore exception
		}
		
		//开始事务
		lr.start_transaction( "Websocket-Connection" );
		
		try {
			
			client.connect();
			lr.end_transaction( "Websocket-Connection", lr.PASS );
			
		} catch ( Throwable e ) {
			
			lr.end_transaction( "Websocket-Connection", lr.PASS );
			logger.error( "Websocket连接失败！", e );
			
			//出错之后仍然进行
			return 0;
		}
		
		return 0;
		
	}

	public int end() throws Throwable {
		client.disconnect();
		logger.debug( "After test." );
		return 0;
	}

}
